<?php
namespace App\Controller;

use lib\View;
use App\Model\Gallery;

class GalleryController
{
    public function index()
    {
        $user = $_SESSION['user'];
        if (empty($user)) {
            header('Location:' . url('auth/signin'));
            return;
        }

        $galleryList = Gallery::get(['user.id' => $user->id]);
        return new View('gallery.index', ['user' => $user, 'galleryList' => $galleryList]);
    }

    public function detail()
    {
        $id = $this->input('id');
        $gallery = Gallery::find(['id' => $id]);
        // return (new View('gallery.detail'))->with('gallery', $gallery);
        $user = $_SESSION['user'];
        return new View('gallery.detail', ['user' => $user, 'gallery' => $gallery]);
    }

    public function create()
    {
        return new View('gallery.create');
    }

    public function store()
    {
        // 创建Gallery对象实例
        $gallery = new Gallery();
        $gallery->id = $this->input('id');
        $gallery->title = $this->input('title');
        $gallery->description = $this->input('description');
        $gallery->created_at = time();
        $gallery->updated_at = $gallery->created_at;

        $user = $_SESSION['user'];
        $gallery->user = $user;

        // 处理上传图片
        $gallery->upload();
        // 保存相册数据
        $gallery->save();
        header('Location:' . url('index'));
    }

    private function input($name)
    {
        return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}